package com.haier.aop;

import com.haier.config.DynamicDataSourceContextHolder;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Aspect
@Order(-1)// 保证该AOP在@Transactional之前执行
@Component
public class DataSourceAop {


    @Before("execution(* com.haier.dao..*.select*(..)) || execution(* com.haier.dao..*.get*(..))")
    public void setReadDataSourceType() {
        DynamicDataSourceContextHolder.setDataSourceType("r");
        System.out.println("dataSource切换到："+DynamicDataSourceContextHolder.getDataSourceType());
    }


    @Before("execution(* com.haier.dao..*.insert*(..)) || execution(* com.haier.dao..*.update*(..))")
    public void setWriteDataSourceType() {
        DynamicDataSourceContextHolder.setDataSourceType("r");
        System.out.println("dataSource切换到："+DynamicDataSourceContextHolder.getDataSourceType());
    }

    @After("execution(* com.haier.dao..*.select*(..)) " +
            "|| execution(* com.haier.dao..*.get*(..)) " +
            "|| execution(* com.haier.dao..*.insert*(..)) " +
            "|| execution(* com.haier.dao..*.update*(..))")
    public void restoreDataSource() {
        System.out.println("dataSource切换到：clean"+DynamicDataSourceContextHolder.getDataSourceType());
        DynamicDataSourceContextHolder.clearDataSourceType();
    }

}